package ejb;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import entities.Volo;

/**
 * Session Bean implementation class VoloBean
 */
@Stateless
public class VoloMgrBean implements VoloMgrBeanLocal {

	@PersistenceContext
    private EntityManager em;

	@Override
	public void aggiungi(VoloDTO volo){
		Volo nuovo = new Volo(volo);
		em.persist(nuovo);
	}
	
	@Override
	public void modifica(VoloDTO volo, int indice){
		Query q = em.createNamedQuery("Volo.MODIFICA");
		q.setParameter("id", indice);
		q.setParameter("compagnia", volo.getCompagnia());
		q.setParameter("partenza", volo.getAeroportoPartenza());
		q.setParameter("arrivo", volo.getAeroportoArrivo());
		q.setParameter("codice", volo.getCodiceVolo());
		q.setParameter("prezzo", volo.getPrezzo());
		q.executeUpdate();	
	}
	
	private Volo trova(int id) {
    	return em.find(Volo.class, id);
    }
	
	public List<?> getVoli() {
    	return em.createNamedQuery("Volo.FIND_ALL", Volo.class).getResultList();
    }

	public void elimina(int indice){
		Query q = em.createNamedQuery("Volo.CANCELLA");
		q.setParameter("id", indice);
		q.executeUpdate();
	}
	
	public VoloDTO getVoloDTO(int indice) {
		Volo volo = trova(indice);
		VoloDTO voloDTO = convertToDTO(volo);
		return voloDTO;
	}

	 public static VoloDTO convertToDTO(Volo volo) {
		VoloDTO voloDTO = new VoloDTO();
		voloDTO.setIdVolo(volo.getIdVolo());
		voloDTO.setAeroportoArrivo(volo.getAeroportoArrivo());
		voloDTO.setAeroportoPartenza(volo.getAeroportoPartenza());
		voloDTO.setCompagnia(volo.getCompagnia());
		voloDTO.setCodiceVolo(volo.getCodiceVolo());
		voloDTO.setPrezzo(volo.getPrezzo());
		return voloDTO;
	}
	 
	public List<VoloDTO> getListaVoliDTO(){
		List<Volo> voli= em.createNamedQuery("Volo.FIND_ALL", Volo.class).getResultList();
		List<VoloDTO> voliDTO = new ArrayList<>();
		for(Volo v: voli){
			voliDTO.add(convertToDTO(v));
		}
		return voliDTO;
	}
}